import React, { useState } from 'react';
import { Button, Input, message, UserIcon, EmailIcon, PasswordIcon } from '@repo/ui';
import styles from './SignIn.module.css';

export interface SignInProps {
  onSignIn?: (userData: {
    username: string;
    email: string;
    password: string;
  }) => void;
  onLogin?: () => void;
  loading?: boolean;
  error?: string;
  className?: string;
}

export const SignIn: React.FC<SignInProps> = ({
  onLogin,
  loading = false,
  error,
  className
}) => {
  const [formData, setFormData] = useState({
    username: '',
    email: '',
    password: ''
  });
  
  const [errors, setErrors] = useState({
    username: '',
    email: '',
    password: ''
  });

  const [agreedToTerms, setAgreedToTerms] = useState(false);

  const validateEmail = (email: string) => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
  };

  const validatePassword = (password: string) => {
    return password.length >= 8;
  };

  const handleInputChange = (field: string, value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }));
    if (errors[field as keyof typeof errors]) {
      setErrors(prev => ({ ...prev, [field]: '' }));
    }
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    
    const newErrors = {
      username: '',
      email: '',
      password: ''
    };

    let hasError = false;

    if (!formData.username) {
      newErrors.username = '请输入用户名';
      hasError = true;
    } else if (formData.username.length < 3) {
      newErrors.username = '用户名至少3个字符';
      hasError = true;
    }

    if (!formData.email) {
      newErrors.email = '请输入邮箱地址';
      hasError = true;
    } else if (!validateEmail(formData.email)) {
      newErrors.email = '请输入有效的邮箱地址';
      hasError = true;
    }

    if (!formData.password) {
      newErrors.password = '请输入密码';
      hasError = true;
    } else if (!validatePassword(formData.password)) {
      newErrors.password = '密码至少8位';
      hasError = true;
    }


    if (!agreedToTerms) {
      hasError = true;
    }

    setErrors(newErrors);

    if (!hasError) {
      // 显示注册提示
      message.warning('暂未开放注册，访客账号guest,密码guest123');
      // onSignIn?.(formData);
    }
  };

  return (
    <div className={`${styles.signinContainer} ${className || ''}`}>
      <div className={styles.signinCard}>
        <div className={styles.signinHeader}>
          <h1 className={styles.signinTitle}>注册账户</h1>
          <p className={styles.signinSubtitle}>创建您的新账户，开始使用我们的服务</p>
        </div>

        <form onSubmit={handleSubmit} className={styles.signinForm}>
          {error && (
            <div className={styles.errorMessage}>
              {error}
            </div>
          )}

          <div className={styles.formGroup}>
            <Input
              type="text"
              label="用户名"
              placeholder="请输入用户名"
              value={formData.username}
              onChange={(e) => handleInputChange('username', e.target.value)}
              error={errors.username}
              required
              disabled={loading}
              prefixIcon={<UserIcon size={16} />}
            />
          </div>

          <div className={styles.formGroup}>
            <Input
              type="email"
              label="邮箱地址"
              placeholder="请输入邮箱地址"
              value={formData.email}
              onChange={(e) => handleInputChange('email', e.target.value)}
              error={errors.email}
              required
              disabled={loading}
              prefixIcon={<EmailIcon size={16} />}
            />
          </div>

          <div className={styles.formGroup}>
            <Input
              type="password"
              label="密码"
              placeholder="请输入密码"
              value={formData.password}
              onChange={(e) => handleInputChange('password', e.target.value)}
              error={errors.password}
              help="密码至少8位"
              required
              disabled={loading}
              prefixIcon={<PasswordIcon size={16} />}
            />
          </div>


          <div className={styles.termsGroup}>
            <label className={styles.termsCheckbox}>
              <input
                type="checkbox"
                checked={agreedToTerms}
                onChange={(e) => setAgreedToTerms(e.target.checked)}
                disabled={loading}
              />
              <span>
                我已阅读并同意
                <button type="button" className={styles.termsLink}>
                  《用户协议》
                </button>
                和
                <button type="button" className={styles.termsLink}>
                  《隐私政策》
                </button>
              </span>
            </label>
            {!agreedToTerms && (
              <div className={styles.termsError}>
                请同意用户协议和隐私政策
              </div>
            )}
          </div>

          <Button
            type="submit"
            variant="default"
            size="lg"
            disabled={loading || !agreedToTerms}
            className={styles.signinButton}
          >
            {loading ? '注册中...' : '注册账户'}
          </Button>
        </form>

        {onLogin && (
          <div className={styles.loginPrompt}>
            <span>已有账户？</span>
            <button
              type="button"
              className={styles.loginLink}
              onClick={onLogin}
            >
              立即登录
            </button>
          </div>
        )}
      </div>
    </div>
  );
};

export default SignIn;
